#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>

int main()
{
    printf("---inet_addr函数测试---\n");
    printf("作用：转换字符串为网络地址以便存入sin_addr_s_addr\n");
    char *addr1 = "1.2.3.4";
    char *addr2 = "1.2.3.256";

    unsigned long conv_addr = inet_addr(addr1);
    if(conv_addr == INADDR_NONE)
    {
        printf("源地址：%s \n",addr1);
        printf("ERROR\n");
    }
    else
    {
        printf("源地址：%s \n",addr1);
        printf("网络序地址: %#lx \n",conv_addr);
    }

    conv_addr = inet_addr(addr2);
    if(conv_addr == INADDR_NONE)
    {
        printf("源地址：%s \n",addr2);
        printf("ERROR\n");
    }
    else
    {
        printf("源地址：%s \n",addr2);
        printf("网络序地址: %#lx \n",conv_addr);
    }

    printf("---inet_aton函数测试---\n");
    printf("作用：转换字符串地址存入sin_addr\n");
    char *addr = "127.232.124.79";
    struct sockaddr_in addr_inet;
    inet_aton(addr,&addr_inet.sin_addr);
    printf("源地址：%s \n",addr);
    printf("网络序地址: %#lx \n",addr_inet.sin_addr.s_addr);

    printf("---inet_ntoa函数测试---\n");
    printf("作用：转换网络字节序整数型地址至字符串\n");
    struct sockaddr_in addr01,addr02;
    char *str_ptr;
    char str_arr[20];

    addr01.sin_addr.s_addr = htonl(0x1020304);
    addr02.sin_addr.s_addr = htonl(0x1010101);
    printf("addr01输入: htonl(0x1020304)\n");
    printf("addr02输入: htonl(0x1010101)\n");
    str_ptr = inet_ntoa(addr01.sin_addr);
    strcpy(str_arr,str_ptr);
    printf("addr01网络序转字符串结果：%s \n",str_ptr);
    //单独运行下面一句，会覆盖掉上面的结果
    //str_arr是我们分配的空间，但str_ptr是暂存区
    inet_ntoa(addr02.sin_addr);
    printf("运行对addr02的inet_ntoa...\n");
    printf("结果会覆盖01：%s \n",str_ptr);
    printf("但01之前已经保存：%s \n",str_arr);


    return 0;


}